/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.service.security;

import java.io.IOException;

import org.gtugs.domain.User;
import org.opensocial.client.OpenSocialClient;
import org.opensocial.client.OpenSocialProvider;
import org.opensocial.client.OpenSocialRequestException;
import org.opensocial.data.OpenSocialPerson;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class FriendConnectUserService implements UserService {

  private HttpServletRequest request;

  public boolean isUserLoggedIn() {
    return getSecurityToken() != null;
  }

  public boolean isUserAdmin() {
    return false;
  }

  public User getUser() {
    String token = getSecurityToken();

    if (token == null) {
      return null;
    }

    OpenSocialPerson viewer = null;
    OpenSocialClient client = new OpenSocialClient(
        OpenSocialProvider.valueOf("FRIENDCONNECT"));
    client.setProperty(OpenSocialClient.Property.TOKEN_NAME, "fcauth");
    client.setProperty(OpenSocialClient.Property.TOKEN, token);

    try {
      viewer = client.fetchPerson();
    } catch (OpenSocialRequestException e) {
      return null;
    } catch (IOException e) {
      return null;
    }

    User user = new User();
    user.setName(viewer.getDisplayName());

    return user;
  }

  public String createLoginUrl(String destinationUrl) {
    throw new UnsupportedOperationException();
  }

  public String createLogoutUrl(String destinationUrl) {
    throw new UnsupportedOperationException();
  }

  public void setRequest(HttpServletRequest request) {
    this.request = request;
  }

  private String getSecurityToken() {
    Cookie[] cookies = request.getCookies();

    for (Cookie cookie : cookies) {
      if (cookie.getName().equals("fcauth14648346865580846398")) {
        return cookie.getValue();
      }
    }

    return null;
  }
}
